import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';

import '../constants.dart';

/// 音乐播放页面
class PlayScreen extends StatefulWidget {
  const PlayScreen({Key? key}) : super(key: key);

  @override
  _PlayScreenState createState() => _PlayScreenState();
}

class _PlayScreenState extends State<PlayScreen> with TickerProviderStateMixin {
  /// 音乐转盘控制器
  late final AnimationController _turntableController = AnimationController(
    // 15秒转一圈
    duration: const Duration(seconds: 15),
    // 防止当前UI不显示动画也在运行，浪费性能，需要with TickerProviderStateMixin
    vsync: this,
    // reverse：重复播放时是否翻转
  )..repeat(reverse: false);

  /// 音乐转盘动画
  late final Animation<double> _turntableAnimation = CurvedAnimation(
    parent: _turntableController,
    curve: Curves.linear,
  );

  /// 点赞控制器
  late final AnimationController _likeController = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 300),
  );

  /// 点赞动画
  late final Animation<double> _likeAnimation = TweenSequence([
    TweenSequenceItem(
        tween: Tween(
          begin: 1.0,
          end: 1.3,
        ).chain(CurveTween(curve: Curves.easeIn)),
        weight: 50),
    TweenSequenceItem(
        tween: Tween(
          begin: 1.3,
          end: 1.0,
        ),
        weight: 50),
  ]).animate(_likeController);

  /// 播放进度
  late double _playProgress = 30.0;

  /// 是否喜欢
  late bool _isLike = false;

  /// 歌曲是否在播放
  late bool _songPlayed = false;

  @override
  void initState() {
    super.initState();
    if (_songPlayed) {
      _turntableController..forward()..repeat();
    } else {
      _turntableController.stop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        backgroundColor: const Color.fromARGB(255, 71, 72, 104),
        body: SafeArea(
          // 整体背景，网易云是动态换背景渐变的，还没研究出来，先这样
          // 感觉是直接取专辑的封面的色调来做的
          child: Container(
            width: double.infinity,
            padding:
                const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color.fromARGB(255, 71, 72, 104),
                  Color.fromARGB(255, 95, 80, 104),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                buildTopBar(),
                buildTurntable(),
                buildAnotherOperation(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 音乐唱片转盘
  RotationTransition buildTurntable() {
    return RotationTransition(
      alignment: Alignment.center,
      turns: _turntableAnimation,
      child: Container(
        width: 285.0,
        height: 285.0,
        padding: const EdgeInsets.all(5.0),
        decoration: const BoxDecoration(
          color: Color.fromARGB(255, 121, 106, 130),
          shape: BoxShape.circle,
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(285.0),
          child: Image.asset("assets/images/discover_card2.jpg"),
        ),
      ),
    );
  }

  /// 底部区域
  Container buildAnotherOperation() {
    /// 自定义图标样式
    IconButton customIcon(IconData icon,
        {Color? color, VoidCallback? onPress}) {
      return IconButton(
        padding: const EdgeInsets.all(0),
        iconSize: 30.0,
        icon: Icon(
          icon,
          color: color ?? Colors.white,
        ),
        onPressed: onPress,
      );
    }

    /// 点击点赞按钮时
    _onTapLike() {
      if (_likeAnimation.status == AnimationStatus.forward ||
          _likeAnimation.status == AnimationStatus.reverse) {
        return;
      }
      setState(() {
        _isLike = !_isLike;
      });
      if (_likeAnimation.status == AnimationStatus.dismissed) {
        _likeController.forward();
      } else if (_likeAnimation.status == AnimationStatus.completed) {
        _likeController.reverse();
      }
    }

    return Container(
      width: double.infinity,
      height: 220.0,
      padding: const EdgeInsets.all(10.0),
      child: Column(
        children: [
          // 点赞、评论等按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ScaleTransition(
                  scale: _likeAnimation,
                  child: _isLike
                      ? IconButton(
                          padding: const EdgeInsets.all(0),
                          iconSize: 30.0,
                          icon: const Icon(
                            Icons.favorite,
                            color: Colors.red,
                          ),
                          onPressed: () {
                            _onTapLike();
                          },
                        )
                      : IconButton(
                          padding: const EdgeInsets.all(0),
                          iconSize: 30.0,
                          icon: const Icon(
                            Icons.favorite_border_outlined,
                            color: Colors.white,
                          ),
                          onPressed: () {
                            _onTapLike();
                          },
                        )),
              customIcon(Icons.file_download_outlined),
              customIcon(Icons.notifications_active_outlined),
              customIcon(Icons.mark_chat_unread_outlined),
              customIcon(Icons.more_vert_outlined),
            ],
          ),
          const SizedBox(
            height: 10.0,
          ),
          // 播放进度条，用Slider实现
          Row(
            children: [
              Text(
                "00:00",
                style: subTextStyle.copyWith(
                  color: Colors.grey,
                ),
              ),
              // 自定义滑轨样式
              Expanded(
                child: SliderTheme(
                  data: const SliderThemeData(
                    // 轨道高度
                    trackHeight: 1.0,
                    // 滑块形状
                    thumbShape: RoundSliderThumbShape(enabledThumbRadius: 5.0),
                  ),
                  child: Slider(
                    inactiveColor: Colors.grey.withOpacity(0.1),
                    activeColor: Colors.white,
                    value: _playProgress,
                    onChanged: (value) {
                      setState(() {
                        _playProgress = value;
                      });
                    },
                    max: 100,
                    min: 0,
                  ),
                ),
              ),
              Text(
                "02:41",
                style: subTextStyle.copyWith(
                  color: Colors.grey,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10.0),
          // 音乐播放遥控器
          SizedBox(
            width: double.infinity,
            height: 80.0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              mainAxisSize: MainAxisSize.max,
              textBaseline: TextBaseline.alphabetic,
              children: [
                customIcon(Icons.loop_outlined),
                customIcon(Icons.skip_previous),
                IconButton(
                  iconSize: 80.0,
                  padding: const EdgeInsets.all(0),
                  icon: Icon(
                    _songPlayed
                        ? Icons.pause_circle_outline
                        : Icons.play_circle_outline_outlined,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    setState(() {
                      _songPlayed = !_songPlayed;
                      if (_songPlayed) {
                        _turntableController..forward()..repeat();
                      } else {
                        _turntableController.stop();
                      }
                    });
                  },
                ),
                customIcon(Icons.skip_next),
                customIcon(Icons.playlist_play_outlined),
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 歌曲信息、回退操作、分享按钮
  SizedBox buildTopBar() {
    /// 自定义图标样式
    Widget customIcon(IconData icon, GestureTapCallback onPress) {
      return IconButton(
        padding: const EdgeInsets.all(0),
        iconSize: 30.0,
        icon: Icon(
          icon,
          color: Colors.white,
        ),
        onPressed: onPress,
      );
    }

    return SizedBox(
      height: 40.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          customIcon(
            Icons.keyboard_arrow_down_outlined,
            () => Navigator.pop(context),
          ),
          Column(
            children: [
              Text(
                "Butterflies",
                style: textStyle.copyWith(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              ),
              Text(
                "Johnny Stimson",
                style: subTextStyle.copyWith(color: Colors.white),
              ),
            ],
          ),
          customIcon(
            Icons.ios_share_outlined,
            () => {},
          ),
        ],
      ),
    );
  }
}
